package com.dyh.quickdemo.bizDemo.GoodsUrl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/*
@Author=Joey Wheeler
@Date=2020/11/4 15:56
*/
@Component
public class PlatformGoodsUrlHelper {

    Logger log = LoggerFactory.getLogger(this.getClass());
    
    public  Map<String, PlatformUrlBuilder> handlerMap = new HashMap<>();
    public final static  PlatformUrlBuilder fallback = (goodsId,skuId)->"";

    interface PlatformUrlBuilder{
        String build(String platformGoodsId,String platformSkuId);
    }

    @Autowired
    PlatformGoodsUrlProp urlProp;

    public String getUrl(ShopSkuDto shopSkuDto){
//        if (shopSkuDto==null){
//            log.error("shopSkuDto 为空");
//            return "";
//        }
//        if (shopSkuDto.getShop()==null){
//            log.error("shopSkuDto 为空");
//            return "";
//        }
//        log
        String platform = shopSkuDto.getShop().getPlatform();
        return getUrl(platform,shopSkuDto.getPlatformNumIid(),shopSkuDto.getPlatformSkuId());
    }

    public String getUrl(String platform,String platformGoodsId,String platformSkuId){
        PlatformUrlBuilder handler = handlerMap.get(platform);
        if (handler==null){
            log.error("找不到对应的url生成方法 平台=",platform);
            handler = fallback;
        }
        return handler.build(platformGoodsId,platformSkuId);
    }

    @PostConstruct
    public void pc(){
        handlerMap.put("TAOBAO",(goodsId,skuId)->{
                    if (StringUtils.isEmpty(skuId))
                        return String.format("%s?id=%s",urlProp.getTaobao(),goodsId);
                    return String.format("%s?id=%s&skuId=%s",urlProp.getTaobao(),goodsId,skuId);
                }
        );

        handlerMap.put("JOS",(goodsId,skuId)->
                String.format("%s/%s.html",urlProp.getJos(),skuId)
                );

        handlerMap.put("PINDUODUO",(goodsId,skuId)->
                String.format("%s?goods_id=%s",urlProp.getPinduoduo(),goodsId)
        );

        handlerMap.put("ALIBABA",(goodsId,skuId)->
                String.format("%s/%s.html",urlProp.getAlibaba(),goodsId)
        );

    }


}
